package org.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.reggie.dto.DishDto;
import org.example.reggie.entry.Dish;
import org.example.reggie.entry.DishFlavor;
import org.example.reggie.mapper.DishMapper;
import org.example.reggie.service.DishFlavorService;
import org.example.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理 service接口实现类
 * 继承mybatis-plus：extends ServiceImpl
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;



    /**
     * 两个事务添加事务管理
     *  @Transactional 开启事务
     *  @EnableTransactionManagement 在启动类加入，支持事务开启
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //dishDto保存后会返回id
        this.save(dishDto);
        List<DishFlavor> flavors =dishDto.getFlavors();
        Long disdId = dishDto.getId();
        //遍历给每一个DishFlavor添加Dishid
        flavors = flavors.stream().map((item)->{
            item.setDishId(disdId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 菜品id查询
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return null;
    }

    /**
     * 更新数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
          this.updateById(dishDto);
          LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
          queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
          dishFlavorService.remove(queryWrapper);

          List<DishFlavor> flavors = dishDto.getFlavors();
          flavors = flavors.stream().map((item)->{
              item.setDishId(dishDto.getId());
              return item;
          }).collect(Collectors.toList());

          dishFlavorService.saveBatch(flavors);
    }

}
